/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.huize.zhike.framework.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 描述:
 *
 * @author tianyuliang
 * @version $Id: JsonSerialUtils.java, v0.1 2020/5/1
 */
public class JsonSerialUtils {

    /**
     * 【保留null字段】将bean序列化为json字符串
     *
     * @param value
     * @return
     */
    public static String writeValueAsJsonString(Object value) {
        try {
            return buildDefaultObjectMapper().writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("serial bean to json error.", e);
        }
    }

    /**
     * 构建默认实例
     *
     * @return
     */
    private static ObjectMapper buildDefaultObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.getFactory().enable(JsonFactory.Feature.INTERN_FIELD_NAMES);
        objectMapper.getFactory().enable(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES);                        // 工厂全局设置
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);                                // 低层级配置
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);                    // 允许属性名称没有引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);                           // 设置解析器
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);                  // 是否允许JSON字符串包含非引号控制字符(值小于32的ASCII字符，包含制表符和换行符)
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);               // 关闭“禁用遇到未知属性,则抛出异常”
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);        // 强制JSON 空字符串("")转换为null对象值

        // 对于空的对象转json的时候不抛出错误,修复异常: Could not write content: No serializer found for Collections and no properties discovered to create BeanSerializer
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);                                   // 禁用序列化日期为timestamps
        objectMapper.setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS);                               // 注意：如果为空则输出
        return objectMapper;
    }

}
